package com.quanquan.parking.ketop.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.quanquan.parking.ketop.exception.EncodeException;
import com.quanquan.parking.ketop.exception.RequestException;
import com.quanquan.parking.ketop.request.BaseRequest;
import com.quanquan.parking.ketop.response.BaseResponse;
import org.apache.commons.io.IOUtils;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BaseApi {

    public static String doApi(BaseRequest request, String apiName)
        throws RequestException, EncodeException
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String url = new StringBuffer().append(KeyTopConfig.URL).append(":").append(KeyTopConfig.PORT).append("/api/").append(apiName).toString();
        String sendStr = "";
        SimpleDateFormat sdfTime = new SimpleDateFormat("yyyyMMddHHmmss:");
        System.out.println(sdfTime.format(new Date()));
        System.out.println(new StringBuffer().append("URL:").append(url));
        System.out.println(new StringBuffer().append("requestData:").append(request));
        
        if (request != null)
        {
            String data;
            try
            {
                data = getEncString(JSON.toJSONString(request), KeyTopConfig.KEY, sdf.format(new Date()));
                sendStr = new StringBuffer().append("{\"data\":\"").append(data).append("\"}").toString();
                System.out.println(new StringBuffer().append("requestStr:").append(sendStr));
            }
            catch (Exception e)
            {
                throw new EncodeException();
            }
        }
        String responseStr = doSendPost(sendStr, url);
        System.out.println(new StringBuffer().append("result:").append(responseStr));
        BaseResponse response = JSON.parseObject(responseStr, BaseResponse.class);
        if (response.getResCode() != 0)
        {
            throw new RequestException(response.getResMsg());
        }
        return response.getData();
    }
    
    protected static String doSendPost(String jsonText, String URL)
    {
        System.out.println(jsonText);
        byte[] jsonData = jsonText.getBytes();
        InputStream instr = null;
        try
        {
            URL url = new URL(URL);
             URLConnection urlCon = url.openConnection();
            //使用代理
//            @SuppressWarnings("static-access")
//            Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress("127.0.0.1", 8888));
//            URLConnection urlCon = url.openConnection(proxy);
            urlCon.setConnectTimeout(3000);
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setUseCaches(false);
            urlCon.setRequestProperty("Content-Type", "application/json");
            urlCon.setRequestProperty("Content-length", String.valueOf(jsonData.length));
            urlCon.setRequestProperty("user", KeyTopConfig.USER);
            urlCon.setRequestProperty("pwd", KeyTopConfig.PWD);
            DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
            printout.write(jsonData);
            printout.flush();
            printout.close();
            instr = urlCon.getInputStream();
            byte[] bis = IOUtils.toByteArray(instr);
            String ResponseString = new String(bis, "UTF-8");
            return ResponseString;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return "";
        }
        finally
        {
            try
            {
                instr.close();
            }
            catch (Exception ex)
            {
                return "";
            }
        }
    }
    
    public static String getEncString(String data, String key, String iv)
        throws Exception
    {
        Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        DESedeKeySpec dks = new DESedeKeySpec(key.getBytes("gb2312"));
        IvParameterSpec ivs = new IvParameterSpec(iv.getBytes("gb2312"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        SecretKey securekey = keyFactory.generateSecret(dks);
        cipher.init(Cipher.ENCRYPT_MODE, securekey, ivs);
        BASE64Encoder base64Encoder = new BASE64Encoder();
        System.out.println(data);
        return base64Encoder.encode(cipher.doFinal(data.getBytes("GB2312")));
    }


    public static JSONObject doApi1(BaseRequest request, String apiName)
            throws RequestException, EncodeException
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String url = new StringBuffer().append(KeyTopConfig.URL).append(":").append(KeyTopConfig.PORT).append("/api/").append(apiName).toString();
        String sendStr = "";
        SimpleDateFormat sdfTime = new SimpleDateFormat("yyyyMMddHHmmss:");
        System.out.println(sdfTime.format(new Date()));
        System.out.println(new StringBuffer().append("URL:").append(url));
        System.out.println(new StringBuffer().append("requestData:").append(request));

        if (request != null)
        {
            String data;
            try
            {
                data = getEncString(JSON.toJSONString(request), KeyTopConfig.KEY, sdf.format(new Date()));
                sendStr = new StringBuffer().append("{\"data\":\"").append(data).append("\"}").toString();
                System.out.println(new StringBuffer().append("requestStr:").append(sendStr));
            }
            catch (Exception e)
            {
                throw new EncodeException();
            }
        }
        String responseStr = doSendPost(sendStr, url);
        System.out.println(new StringBuffer().append("result:").append(responseStr));
        return JSON.parseObject(responseStr);
    }

}
